package com.md.config.database;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.md.value.constants.DefaultServerContext;
import com.md.value.server.ServerContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author 刘骄阳
 * 2022-04-06 17:42
 */
@Component
@ConditionalOnClass(value = {MybatisPlusInterceptor.class})
public class MyMetaObjectHandler implements MetaObjectHandler {
  /**
   * 插入元对象字段填充（用于插入时对公共字段的填充）
   *
   * @param metaObject 元对象
   */
  @Override
  public void insertFill(final MetaObject metaObject) {
    LocalDateTime now = LocalDateTime.now();
    Long userId = Optional.ofNullable(ServerContext.getUserId()).
      orElse(0L);
    metaObject.setValue("updateDate", now);
    metaObject.setValue("createDate", now);
    metaObject.setValue("createBy", userId);
    metaObject.setValue("updateBy", userId);
    metaObject.setValue("version", 0);
  }

  /**
   * 更新元对象字段填充（用于更新时对公共字段的填充）
   *
   * @param metaObject 元对象
   */
  @Override
  public void updateFill(final MetaObject metaObject) {
    metaObject.setValue("updateDate", LocalDateTime.now());
    metaObject.setValue("updateBy", Optional.ofNullable(ServerContext.
      getLong(DefaultServerContext.USER_ID)).orElse(0L));
  }

}
